﻿using StockViz.Data.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace StockViz.Data
{
    public class YahooClient
    {
        //https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22YHOO%22%20and%20startDate%20%3D%20%222009-09-11%22%20and%20endDate%20%3D%20%222010-03-10%22
        //http://ichart.finance.yahoo.com/table.csv?s=^GSPC&ignore=.csv
        public async Task<List<YahooStockQuote>> GetHistorical(DateTime startDate, DateTime endDate, string symbol)
        {
            List<YahooStockQuote> response = null;
            var request = "table.csv?" +
                          $"s={symbol.Trim()}&" +
                          $"a={startDate.Month - 1:00}&b={startDate.Day:00}&c={startDate.Year}&" +
                          $"d={endDate.Month - 1:00}&e={endDate.Day:00}&f={startDate.Year}&" +
                          "g=d&ignore=.csv";
            //http://ichart.finance.yahoo.com/table.csv?s=WU&a=01&b=19&c=2010&d=01&e=19&f=2010&g=d&ignore=.csv

            using (var client = GetClient())
            {
                try
                {
                    client.BaseAddress = new Uri("http://ichart.finance.yahoo.com/" + request);
                    var responseString = await client.GetStringAsync(string.Empty);
                    response = DeserializeResults(responseString, symbol);
                }
                catch (Exception ex)
                {
                }
            }
            return response;
        }

        private List<YahooStockQuote> DeserializeResults(string results, string symbolName)
        {
            return results
                .Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
                .Skip(1)
                .Select(x =>
                {
                    var fields = x.Replace("\r", string.Empty).Split(',');
                    return new YahooStockQuote()
                    {
                        Date = DateTime.Parse(fields[0]),
                        Open = float.Parse(fields[1]),
                        High = float.Parse(fields[2]),
                        Low = float.Parse(fields[3]),
                        Close = float.Parse(fields[4]),
                        Volume = long.Parse(fields[5]),
                        AdjustedClose = float.Parse(fields[6]),
                        Symbol = symbolName
                    };
                })
                .ToList();
        }

        private HttpClient GetClient()
        {
            HttpClientHandler handler;
            if (Environment.UserDomainName == "FMER")
                handler = new HttpClientHandler()
                {
                    UseProxy = true,
                    Proxy = new WebProxy("http://FM-PROXYBC.FIRSTMERIT.LOCAL:8080")
                    {
                        UseDefaultCredentials = true,
                        Credentials = CredentialCache.DefaultCredentials
                    }
                };
            else
            {
                handler = new HttpClientHandler();
            }
            var client = new HttpClient(handler) { BaseAddress = new Uri("http://ichart.finance.yahoo.com/") };
            return client;
        }
    }
}